import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Server } from 'socket.io';
import { Socket } from 'node:dgram';

const app = express();
const server = createServer(app);
const io = new Server(server);

const __dirname = dirname(fileURLToPath(import.meta.url));

const userSockets = {};
const socketObjs = {};

app.get('/', (req, res) => {
  res.sendFile(join(__dirname, 'index.html'));
});

io.on('connection', (socket) => {
  console.log('a user connected');
  console.log('socket id: ' + socket.id);
 
  // 监听 'user info' 事件，获取参数
  socket.on('user info', userInfo => {
    const userId = userInfo.userId;
    console.log('User ID:', userId);
    userSockets[userInfo.userId] = socket.id;
    // socketObjs[userInfo.userId] = socket;
   
  });

  // 监听‘private message’ 事件
  socket.on('private message', (msg, callback) => {
    console.log('message: ' + msg)
    if (typeof msg == 'object' && msg != null) {
        if ('content' in msg) {
            console.log('receive message: ' + msg.content + ' from: ' + msg.from + ' to: ' + msg.to)
        }
    }

    const timestamp = Date.now();

    const msgId = 'id'  +timestamp.toString();

    const fullMsg = {
        from: msg.from,
        to: msg.to,
        content : msg.content,
        createTime: timestamp,
        fromType: msg.fromType,
        type: msg.type,
        msgId: msgId,
    }


    callback({
      status: 'ok',
      message: fullMsg
    });


    // 获取消息的目标用户 id
    const targetUserId = msg.to;

    // 查找目标用户的 socket id
    const targetSocketId = userSockets[targetUserId];

    // 如果目标用户在线，则向目标用户发送消息
    if (targetSocketId) {
        console.log('transmit message: ' + fullMsg.content + ' from: ' + fullMsg.from + ' to: ' + fullMsg.to)
        socket.to(targetSocketId).timeout(10000).emit('private message', fullMsg, (err, response) => {
            if (err) {
              console.log(err)
            } else {
                let keys = Object.keys(response);  
                for (let i = 0; i < keys.length; i++) {  
                    console.log(keys[i], response[keys[i]]);  
                }
                const res = response['0']
                if (res != null) {
                    console.log('callback: ' + res.status + ' laizi: ' + fullMsg.to)
                }
            }  
        });
        /*
        socket.to(targetSocketId).timeout(5000).emit('private message', array, (err, response) => {
            if (err) {
              console.log(err)
            } else {
              console.log('callback r: ' + response);
              console.log('callback: ' + response.status); // 'ok'
            }  
        });
        */
        /*
        io.to(targetSocketId).timeout(5000).emit('private message', array, (err, response) => {
            if (err) {
              console.log(err)
            } else {
              console.log('callback r: ' + response);
              console.log('callback: ' + response.status); // 'ok'
            }  
        });
        */
      
    } else {
        console.log('Target user is not online.')
        callback({ status: 'error', message: 'Target user is not online.' });
    }

    
  
    //socket.to(msg.to).to(msg.from).emit
    
    /*
    setTimeout(() => {
        const timestamp = Date.now();
        const msgId = 'id'  +timestamp.toString();
        const autoReply = {
            from: fullMsg.to,
            to: fullMsg.from,
            content : '这是一个自动回复',
            createTime: timestamp,
            fromType: 'assistant',
            type: 'text',
            messageId: msgId,
    
        }

        const array = [];

        // 将对象添加到数组中
        array.push(autoReply);
        
        // 收到消息时进行消息转发
        socket.timeout(5000).emit('private message', array, (err, response) => {
            if (err) {
              console.log(err)
            } else {
              console.log(response.status); // 'ok'
            }  
        });
    }, 2000);
    */


  });
});

server.listen(3000, () => {
  console.log('server running at http://localhost:3000');
});
